<section class="page-wrapper orders-body">
    <div class="table-order-list">
        <div id="unconfirmed-orders" class="order-group" style="display: none;">
            <div class="title">
                <div class="text">待处理</div>
            </div>
        </div>

        <div id="confirmed-orders" class="order-group" style="display: none;">
            <div class="title">
                <div class="text">进行中</div>
            </div>
        </div>

        <div class="no-message" style="display: none">当前没有要处理的订单(^=^)</div>

    </div>

    <div id="repeat-waiter-home-order" class="order-g-item" style="display: none;">
        <div class="table-name">A12</div>
        <div class="message">
            <div class="line waiter-home-order-number">订单编号：<span class="text">22</span></div>
            <div class="line waiter-home-order-time">下单时间：<span class="text">2016-09-18 10:14</span>
            </div>
            <div class="line waiter-home-order-from">订单来源：<span class="text">微信(vision_小词)</span>
            </div>
        </div>
        <div class="order-op">
            <div class="price waiter-home-order-price">￥328</div>
            <div class="compound">(优惠: <span class="text">￥20</span>)</div>
            <div class="btns">
                <button class="btn white waiter-home-order-append">拒绝</button>
                <button class="btn waiter-home-order-pay">结账</button>
            </div>
        </div>
    </div>
    <script>

        (function () {
            "use strict";

            window.OrderState = {
                confirmed: 0, //已确认订单
                wechat_payed: 1, //已通过微信支付的订单
                unconfirmed: 2, // 为确认订单
                cart_message: 3, // 购物车信息
                scan_qr_payed: 4, // 扫描
                offline_payed: 5,
                refused: 6
            }

            var $repeatWaiterHomeOrderItem = undefined;

            function cloneWaiterHomeOrderItem() {
                if (!$repeatWaiterHomeOrderItem) {
                    $repeatWaiterHomeOrderItem = $('#repeat-waiter-home-order');
                }
                var $item = $repeatWaiterHomeOrderItem
                        .clone()
                        .show()
                        .attr('id', '');
                return $item;
            }

            var timerId;
            var lastGetterTime;
            //订单
            function getStoreOrders() {//获取待确认订单...
                $.getJSON('/waiterOrder/api/getStoreConfirmOrder/' + storeId + '/0', '', function (data) {
                    console.log(data);
                    lastGetterTime = data.lastUpdateDate;
                    if (data && data.total) {
                        hideNoOrders();
                        console.log('getStoreConfirmOrder');
                        showUnconfirmedOrderList(data.result);
                    } else {
                        console.log('no data');
                        showNoOrders();
                    }

                }).fail(function () {
                    showNoOrders();
                });
                //未支付订单列表
                $.getJSON('/waiterOrder/api/getStoreNopayOrder/' + storeId + '/0', '', function (data) {
                    console.log(data);

                    if (data && data.total) {
                        hideNoOrders();
                        console.log('getStoreNopayOrder');
                        showConfirmedOrderList(data.result);
                    } else {
                        console.log('no data');
                        showNoOrders();
                    }
                }).fail(function () {
                    showNoOrders();
                });

                cycleGetter();
            }

            function stopCycleGetter() {
                if (timerId) {
                    clearInterval(timerId);
                }
            }

            /**
             * 每隔10s从服务器获取一次数据
             */
            function getDiff() {
                var url = '/waiterOrder/api/getOrderNotifyList/' + window.storeId;
                console.log(lastGetterTime);

                if (!lastGetterTime) return;

                $.post(url, {lastUpdateDate: lastGetterTime}, function (data) {
                    console.log(data);

                    if (data && data.lastUpdateDate) {
                        lastGetterTime = data.lastUpdateDate;
                    }

                    if (data && data.confirmOrderList && data.confirmOrderList.length) { //待确认列表数据发生变化
                        hideNoOrders();
                        var list = data.confirmOrderList;
                        $.each(list, function (index, item) {
                            if (item.state == OrderState.unconfirmed) {
                                showUnconfirmedOrderItem(item);
                            } else { //从待确认列表中删除对应项
                                console.log($('#unconfirmed-orders .order-g-item[order-id=' + item.orderId + ']'));
                                $('#unconfirmed-orders .order-g-item[order-id=' + item.orderId + ']').fadeOut(function(){
                                    console.log($(this));
                                    $(this).remove();
                                    ifHideUnconfirmedList();
                                });

                            }
                        });
                    }

                    if (data && data.nopayOrderList && data.nopayOrderList.length) {
                        hideNoOrders();
                        var list = data.nopayOrderList;
                        $.each(list, function (index, item) {
                            var $item = $('#confirmed-orders .order-g-item[order-id=' + item.orderId + ']');
                            if (item.state == OrderState.confirmed) { //在 进行中 列表添加或者修改Item

                                if ($item.length > 0) { //update
                                    setOrderItemCommonStatus($item, item);
                                } else {  //新增
                                    //showConfirmedOrderList()
                                    showConfirmedItem(item, true);
                                }

                            } else { //删除
                                $item.fadeOut(function () {
                                    $item.remove();
                                    ifHideConfirmedList();
                                });
                            }
                        });
                    }

                });
            }

            function cycleGetter() {
                timerId = setInterval(getDiff, 10 * 1000);
            }

            window.getDiff = getDiff;
            window.cycleGetter = cycleGetter;

            function resetConfirmedOrdersList() {
                $('#confirmed-orders').hide().children('.order-g-item').remove();
            }

            function resetUnconfirmedOrdersList() {
                $('#unconfirmed-orders').hide().children('.order-g-item').remove();
            }

            function setConfirmedOrderItem($item) {
                if ($('#confirmed-orders').is(':hidden')) {
                    console.log('显示 confirmed-orders');
                    $('#confirmed-orders').show();
                }
                $item.find('.waiter-home-order-append').hide();
                $item.find('.waiter-home-order-pay').on('click', function () {

                    var orderId = $(this).parents('.order-g-item').attr('order-id');
                    //收款
                    //location.href = "#action=waiter_qr&from=首页&tableId=" + tId;
                    if (confirm('确定进行线下结账？')) {
                        offlinePay(orderId);
                    }

                    return false;
                }).text('结账');
            }

            /**
             * 线下结账
             */
            function offlinePay(orderId) {
                var $item = $('.order-g-item[order-id=' + orderId + ']');
                api.offlinePay(orderId, window.userId, function (data) {//success
                    $item = $('.order-g-item[order-id=' + orderId + ']');
                    $item.fadeOut(function () {
                        $item.remove();
                        ifHideConfirmedList();
                    });
                }, function () {//error
                    //提示结账失败
                    var tableName = $item.find('.table-name').text();
                    common.toast(tableName + ' 桌结账失败，请检测网络...');
                })
            }


            function setOrderItemCommonStatus($item, orderItem) {

                var orderId = orderItem.orderId;
                var time = orderItem.createDate;
                var price = common.fixOne(orderItem.price);
                var tId = orderItem.tableId;
                var tableName = orderItem.tableName
                var attrId = orderItem.state == OrderState.confirmed ? 'order-id' : 'sub-order-id';
                $item.attr(attrId, orderId);
                $item.attr('table-id', tId);
                $item.find('.table-name').text(tableName);
                $item.find('.waiter-home-order-number .text').text(orderId);
                $item.find('.waiter-home-order-time .text').text(time);
                $item.find('.waiter-home-order-price').text('￥' + price);
            }


            /**
             * 取消订单
             */
            function refuse(id, $item) {
                console.log('refuse ' + id);

                if (confirm("您确定拒绝此订单吗？")) {
                    $.getJSON('/waiterOrder/api/refuseOrder/' + id, '', function (data) {
                        if (data.status === 'success') {
                            common.toast('订单已拒绝');
                            $item.fadeOut(function () {
                                $item.remove();
                                if ($('#nconfirmed-orders .order-g-item').length == 0) {
                                    $('#unconfirmed-orders').fadeOut();
                                }
                            });
                            ifHideUnconfirmedList();
                        } else {
                            common.toast('拒绝订单失败');
                        }
                    });
                }
            }

            /**
             * 接受订单
             */
            function accept(id, $item) {
                console.log('accept ' + id);
                $.getJSON('/waiterOrder/api/acceptOrder/' + id, '', function (data) {
                    console.log(data);
                    if (data.status === 'success') {
                        $item.fadeOut(function () {
                            console.log($(this));
                            $(this).remove();
                            ifHideUnconfirmedList();
                        });
                        getDiff();
                    } else {
                        common.toast('接受订单失败');
                    }
                });
            }

            function showConfirmedOrderList(orders) {
                resetConfirmedOrdersList();
                console.log(orders);
                $.each(orders, function (index, orderItem) {
                    showConfirmedItem(orderItem);
                });
            }

            function showConfirmedItem(orderItem, isPrepend) {
                if (orderItem.state === OrderState.confirmed) {
                    var $item = cloneWaiterHomeOrderItem();
                    setOrderItemCommonStatus($item, orderItem);
                    $item.on('click', function () {
                        var oId = $(this).attr('order-id');
                        //location.href = "#action=waiter_order&orderId=" + oId + '&from=首页';
                        location.href = "#action=orderDetail&orderId=" + oId;
                    });
                    setConfirmedOrderItem($item);
                    if (isPrepend) {
                        $('#confirmed-orders .title').after($item);
                    } else {
                        $('#confirmed-orders').append($item);
                    }

                }
            }

            function ifHideConfirmedList() {
                if (!$('#confirmed-orders .order-g-item').length) {
                    $('#confirmed-orders').hide();
                    showNoOrders();
                }
            }


            /**
             * 显示未确认订单
             * @param orders
             */
            function showUnconfirmedOrderList(orders) {
                resetUnconfirmedOrdersList();
                console.log(orders);
                $.each(orders, function (index, orderItem) {
                    showUnconfirmedOrderItem(orderItem);
                });
            }

            /**
             * 判断是否需要隐藏未确认的列表
             */
            function ifHideUnconfirmedList() {
                if (!$('#unconfirmed-orders .order-g-item').length) {
                    $('#unconfirmed-orders').hide();

                    showNoOrders();
                }
            }

            function showUnconfirmedOrderItem(orderItem) {
                if (orderItem.state === OrderState.unconfirmed) {
                    if ($('#unconfirmed-orders').is(':hidden')) {
                        console.log('显示 unconfirmed-orders');
                        $('#unconfirmed-orders').show();
                        hideNoOrders();
                    }

                    var $item = cloneWaiterHomeOrderItem();
                    setOrderItemCommonStatus($item, orderItem);
                    $item.on('click', function () {
                        var oId = $(this).attr('sub-order-id');
                        location.href = "#action=orderDetail&subOrderId=" + oId;
                    });
                    $item.find('.waiter-home-order-append')
                            .show()
                            .on('click', function () {
                                var $parent = $(this).parents('.order-g-item');
                                var subOrderId = $parent.attr('sub-order-id');
                                refuse(subOrderId, $parent);
                                return false;
                            }).text('拒绝');
                    $item.find('.waiter-home-order-pay')
                            .show()
                            .on('click', function () {

                                var $parent = $(this).parents('.order-g-item');
                                var subOrderId = $parent.attr('sub-order-id');

                                accept(subOrderId, $parent);

                                return false;
                            }).text('确认');
                    $('#unconfirmed-orders').append($item);
                }
            }

            /**
             * 隐藏没有订单时的提示信息
             *
             */
            function hideNoOrders() {
                $('.orders-body .no-message').hide();
            }

            /**
             * 显示没有订单情况下的提示
             */
            function showNoOrders() {
                if ($('#unconfirmed-orders').is(':hidden') && $('#confirmed-orders').is(':hidden')) {
                    var height = $('.orders-body').height();
                    $('.orders-body .no-message').css({'line-height': height + 'px', 'text-align': 'center'}).fadeIn();
                }
            }

            getStoreOrders();
        }());
    </script>
</section>
